package com.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.community.entity.Pet;
import com.community.service.PetService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("pet")
public class PetController extends ApiController {

    @Resource
    PetService petService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param pet  查询实体
     * @return 所有数据
     */
    @RequestMapping("petlist")
    @ResponseBody
    public R selectAll(Page<Pet> page, Pet pet) {
        page.setSize(4);
        QueryWrapper<Pet> wrapper = new QueryWrapper<>();
        wrapper.eq("1", 1);
        wrapper.like(pet.getVariety() != null, "variety", pet.getVariety());
        wrapper.between(pet.getBeginDate() != null && pet.getOverDate() != null,
                "pet.create_date", pet.getBeginDate(), pet.getOverDate());
        return success(this.petService.selectAll(page, wrapper));
    }

    @RequestMapping("tolist")
    public String toList() {
        return "pet_list";
    }

    @GetMapping("delete")
    @ResponseBody
    public R delete(@RequestParam("idList") String parm) {
        List<String> list = Arrays.asList(parm.split(","));
        return success(this.petService.removeByIds(list));
    }

    @GetMapping("petdel")
    @ResponseBody
    public R petdelete(@PathVariable("id") Integer id) {
        return success(this.petService.removeById(id));
    }

    @RequestMapping("toadd")
    public String toAdd() {
        return "pet_add";
    }

    @GetMapping("{id}")
    @ResponseBody
    public R addAndUpdata(@PathVariable Integer id) {
        return success(petService.getPetByIdBiz(id));
    }


    @PostMapping("update")
    @ResponseBody
    public R updatePet(Pet pet) {
        pet.setCreateDate(new Date());
        System.out.println(pet.toString());
        return success(petService.updateById(pet));
    }


    @PostMapping("add")
    @ResponseBody
    public R addPet(Pet pet) {
        pet.setCreateDate(new Date());
        //return null;
        return success(petService.save(pet));
    }
}
